package io.zhengsh.vvip.leetcode.tree;

public class Q572_subtree_of_another_tree {

    /**
     * Definition for a binary tree node.
     */
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    class Solution {
        public boolean isSubtree(TreeNode s, TreeNode t) {
            return dfs(s, t);
        }

        private boolean dfs(TreeNode s, TreeNode t) {
            if (s == null) {
                return false;
            }
            return check(s, t) || dfs(s.right, t) || dfs(s.left, t);
        }

        private boolean check(TreeNode s, TreeNode t) {
            if (s == null && t == null) {
                return true;
            }
            if (s == null || t == null || s.val != t.val) {
                return false;
            }
            return check(s.left, t.left) && check(s.right, t.right);
        }
    }
}
